package com.eptok.weixin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.eptok.weixin.util.LogUtil;
import com.eptok.weixin.util.MessageUtil;
import com.eptok.weixin.util.RespMessageUtil;

import hikefa.core.remote.client.RemoteCall;
import hikefa.core.util.Base16;
import hikefa.core.util.StringUtil;
import hikefa.core.util.security.JDigest;
import net.sf.json.JSONObject;
import yspay.express.bean.CheckBean;
import yspay.express.bean.responsemessage.Image;
import yspay.express.bean.responsemessage.ResponseArticle;
import yspay.express.bean.responsemessage.ResponseImageMessage;
import yspay.express.bean.responsemessage.ResponseNewsMessage;
import yspay.express.bean.responsemessage.ResponseTextMessage;
import yspay.express.store.WxConstant;
import yspay.express.store.WxStore;
import yspay.express.util.CommonUtil;
import yspos.cpfs.express.entity.ExpWebchatUserinfo;
import yspos.cpfs.remoteserver.iface.IExpressService;


public class CoreService {
	

	private static final Logger log = Logger.getLogger(CoreService.class);
	
	private IExpressService iexpressServer = (IExpressService) RemoteCall.getRemoteObject(IExpressService.class);
	
	/**
	 * 处理微信发送过来的请求
	 * 
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	public String processRequest(HttpServletRequest request,CheckBean bean) throws Exception {
		
		String respxml = null;
		try {
			//解析xml
			Map<String, String> requestMap = MessageUtil.parseXml(request,bean);
			
			//获取发送方账号
			String fromUserName = requestMap.get("FromUserName");

			//开发者公众号
			String toUserName = requestMap.get("ToUserName");
			
			//获取消息类型
			String msgType = requestMap.get("MsgType");
			log.debug("MsgType:"+msgType);
			
			//消息类型为事件
			if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {

				//获取事件类型
				String eventType = requestMap.get("Event");
				log.debug("eventType:"+eventType);
				
				respxml = this.dealEvent(fromUserName, toUserName, eventType,requestMap);

				
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				
				//获取用户回复的内容
				String content = requestMap.get("Content");
				log.debug("获取用户回复的内容："+content);
				
				if(content.indexOf("图文") != -1)
				{
					//图文消息
					respxml = tuwen(fromUserName, toUserName);
				}else if(content.equals("1"))
				{
					respxml = randImg(fromUserName, toUserName);
				}else if(content.indexOf("快递") != -1)
				{
					respxml = dealUserrequest(fromUserName, toUserName, "您的快递模板消息已发送");
				}else
				{
					respxml = dealUserrequest(fromUserName, toUserName, content);
				}
				
				
			}
			
		} catch (Exception e) {
			log.error("解析用户信息时出现问题",e);
		}
		log.info("回复给用户的消息加密前：\n"+respxml);
		
		//WXBizMsgCrypt wc = new WXBizMsgCrypt(GeneralConstant.TOKEN, GeneralConstant.ENCODING_AES_KEY, GeneralConstant.APPID);

		//String afterEncrypt = wc.encryptMsg(respxml, timeStamp, nonce);
		
		//LogUtil.APP.info("回复给用户的消息加密后：\n"+afterEncrypt);
		
		//返回加密数据
//		return afterEncrypt;
		return respxml;
	}
	
	
	
	
	private String dealEvent(String fromUserName,String toUserName,String eventType,Map<String, String> requestMap) throws Exception {
		String respxml = null;
		//事件类型为订阅
		if(eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
			//欢迎语
			ResponseTextMessage helloMessage =  RespMessageUtil.getHelloMessage(fromUserName, toUserName);
			respxml = MessageUtil.textMsgToXml(helloMessage);
			
			//saveUser(fromUserName,true,toUserName);
			
		}else if(eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
			//如果是取消关注，则删除绑定关系
			//weixCardRalationMgr.deleteRalation(fromUserName);
			//saveUser(fromUserName,true,toUserName);
			
		}else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
			
			String eventKey = requestMap.get("EventKey");
			respxml = this.dealClickEvent(fromUserName, toUserName, eventKey);
			
		}
		
		return respxml;
	}
	
	/**
	 * 处理用户请求
	 * @param fromUserName  用户openID
	 * @param toUserName 开发者公众号
	 * @param content 用户回复的对应内容
	 * @return
	 * @throws Exception 
	 */
	private String dealUserrequest(String fromUserName,String toUserName,String content) throws Exception {
		
		String respxml = null;
		
		String openId = Base16.bytesToHexStr(JDigest.digestMD5((fromUserName).getBytes("UTF-8"))).toLowerCase();
		
		LogUtil.APP.debug("加密后的ipenID:"+openId);
		
		ResponseTextMessage textMessage = RespMessageUtil.getinit(fromUserName, toUserName);
		textMessage.setContent(content);
		respxml = MessageUtil.textMsgToXml(textMessage);
		
		return respxml;
		
	}
	
	private String dealClickEvent(String fromUserName,String toUserName,String eventKey )throws Exception{
		String respxml = null;
		
		ResponseTextMessage textMessage = RespMessageUtil.getinit(fromUserName, toUserName);
		if(eventKey.equals(WxConstant.KEY_HELP_YOURSELF))
		{
			textMessage.setContent("请自便");
		}else if(eventKey.equals(WxConstant.KEY_HELP_WORKER))
		{
			textMessage.setMsgType("transfer_customer_service");
			textMessage.setContent("稍候有客服与您联系，请等待");
		}
		respxml = MessageUtil.textMsgToXml(textMessage);

		return respxml;
	}
	
	/**
	 * 发送随机图片
	 * @param fromUserName
	 * @param toUserName
	 * @return
	 * @throws Exception
	 */
	private String randImg(String fromUserName,String toUserName) throws Exception {
		
		String respxml = null;
		String ret = ImageService.upload();
		JSONObject json = JSONObject.fromObject(ret);
		String openId = Base16.bytesToHexStr(JDigest.digestMD5((fromUserName).getBytes("UTF-8"))).toLowerCase();
		
		LogUtil.APP.debug("加密后的ipenID:"+openId);
		
		ResponseImageMessage imgMessage = RespMessageUtil.getInitImage(fromUserName, toUserName);
		Image img = new Image();
		img.setMediaId(json.getString("media_id"));
		imgMessage.setImage(img);
		respxml = MessageUtil.imageMsgToXml(imgMessage);
		
		return respxml;
		
	}
	
	/**
	 * 图文消息
	 * @param fromUserName  用户openID
	 * @param toUserName 开发者公众号
	 * @param content 用户回复的对应内容
	 * @return
	 * @throws Exception 
	 */
	private String tuwen(String fromUserName,String toUserName) throws Exception {
		
		String respxml = null;
		
		String openId = Base16.bytesToHexStr(JDigest.digestMD5((fromUserName).getBytes("UTF-8"))).toLowerCase();
		
		LogUtil.APP.debug("加密后的ipenID:"+openId);
		
		ResponseNewsMessage newsMessage = RespMessageUtil.getInitNews(fromUserName, toUserName);
		
		
		
		List<ResponseArticle> arts = new ArrayList<ResponseArticle>();
		ResponseArticle art = new ResponseArticle();
		art.setDiscription("这是妈咪权描述");
		art.setPicUrl("http://img.mp.itc.cn/upload/20160512/3ccafeae9a1c474a8c473d3f2b8d1671_th.jpg");
		art.setTitle("妈咪权");
		art.setUrl("https://www.baidu.com");
		
		ResponseArticle art2 = new ResponseArticle();
		art2.setDiscription("这是妈咪权描述");
		art2.setPicUrl("http://img.mp.itc.cn/upload/20160512/3ccafeae9a1c474a8c473d3f2b8d1671_th.jpg");
		art2.setTitle("妈咪权1");
		art2.setUrl("https://www.baidu.com");
		
		ResponseArticle art3 = new ResponseArticle();
		art3.setDiscription("这是妈咪权描述");
		art3.setPicUrl("http://img.mp.itc.cn/upload/20160512/3ccafeae9a1c474a8c473d3f2b8d1671_th.jpg");
		art3.setTitle("妈咪权2");
		art3.setUrl("https://www.baidu.com");
		
		ResponseArticle art4 = new ResponseArticle();
		art4.setDiscription("这是妈咪权描述");
		art4.setPicUrl("http://img.mp.itc.cn/upload/20160512/3ccafeae9a1c474a8c473d3f2b8d1671_th.jpg");
		art4.setTitle("妈咪权3");
		art4.setUrl("https://www.baidu.com");
		
		ResponseArticle art5 = new ResponseArticle();
		art5.setDiscription("这是妈咪权描述");
		art5.setPicUrl("http://img.mp.itc.cn/upload/20160512/3ccafeae9a1c474a8c473d3f2b8d1671_th.jpg");
		art5.setTitle("妈咪权4");
		art5.setUrl("https://www.baidu.com");
		
		ResponseArticle art6 = new ResponseArticle();
		art6.setDiscription("这是妈咪权描述");
		art6.setPicUrl("http://img.mp.itc.cn/upload/20160512/3ccafeae9a1c474a8c473d3f2b8d1671_th.jpg");
		art6.setTitle("妈咪权5");
		art6.setUrl("https://www.baidu.com");
		
		arts.add(art);
		arts.add(art2);
		arts.add(art3);
		arts.add(art4);
		arts.add(art5);
		arts.add(art6);
		newsMessage.setArticles(arts);
		newsMessage.setArticleCount(arts.size());
		respxml = MessageUtil.newsMsgToXml(newsMessage);
		
		return respxml;
		
	}
	
	
	/**
	 * 保存用户信息 
	 * @param openid
	 * @param isSubscribe true:关注 false:取消关注
	 */
	public boolean saveUser(String openid,boolean isSubscribe,String toUserName)
	{
		/*获取用户信息 并保存数据库*/
		String token = WxStore.getAccessToken();
		if(StringUtil.isEmpty(token))
		{
			log.error("保存微信用户信息(openid:"+openid+")失败：获取token 失败；");
			return false;
		}
		String requestUrl = WxConstant.USER_GETBYID_URL_ADMIN.replace("ACCESS_TOKEN",token);
		requestUrl = requestUrl.replace("OPENID", openid);
		JSONObject jsonObject = null;
		
		//找到这条信息
		ExpWebchatUserinfo user = null;
				
		try {
			jsonObject = CommonUtil.httpsRequest(requestUrl,CommonUtil.REQ_GET,null);
			if(jsonObject == null )
			{
				log.error("保存微信用户信息(openid:"+openid+")失败：从微信接口获取用户信息失败；");
				return false;
			}
			user = iexpressServer.webchatUserinfoLoad(openid);
			if(jsonObject.getString("subscribe").equals("1"))//关注  有数据
			{
				if(user == null) {
				user = new ExpWebchatUserinfo();
				/*基本信息*/
				user.setCity(jsonObject.getString("city"));
				user.setCountry(jsonObject.getString("country"));
				user.setHeadimgUrl(jsonObject.getString("headimgurl"));
				user.setLanguage(jsonObject.getString("language"));
				user.setNickname(jsonObject.getString("nickname"));
				user.setOpenId(jsonObject.getString("openid"));
				user.setOriginal(toUserName);
				user.setProvince(jsonObject.getString("province"));
				user.setSex(jsonObject.getString("sex"));
				/*基本信息*/
				user.setSubscribeTm(new Date(jsonObject.getLong("subscribe_time")*1000L));
				user.setState(jsonObject.getString("subscribe"));
				user.setUnSubscribeTm(null);}
				if(user.getCreateTm() == null)//说明是刚刚新建的对象
				{
					iexpressServer.webchatUserinfoSave(user);
				}else
				{
					iexpressServer.webchatUserinfoUpdate(user);
				}
			}else//取消关注
			{
				if(user != null)
				{
					user.setUnSubscribeTm(new Date());
					user.setState(jsonObject.getString("subscribe"));
					iexpressServer.webchatUserinfoUpdate(user);
				}
			}
			
			log.info("save WebchatUserinfo success !! ");
			return true;
		} catch (Exception e) {
			log.error("save WebchatUserinfo error："+e.getMessage());
			return false;
		}
	}
}




